<template>
  <div class="app-container">
    <!-- 页面头部和操作区域 -->
    <div class="page-header-compact">
      <div class="header-row">
        <!-- 左侧：标题和统计信息 -->
        <div class="header-left">
          <h1 class="page-title">
            <svg-icon icon-class="money" style="margin-right: 8px; color: #1EB7E6;" />
            结算信息跟踪
          </h1>
          <div v-if="stats" class="stats-inline">
            <span class="stat-item">总计: <strong>{{ stats.total || 0 }}</strong></span>
            <span class="stat-item pending">待填写: <strong>{{ stats.pending_count || 0 }}</strong></span>
            <span class="stat-item processing">填写中: <strong>{{ stats.filling_count || 0 }}</strong></span>
            <span class="stat-item completed">已完成: <strong>{{ stats.completed_count || 0 }}</strong></span>
          </div>
        </div>

        <!-- 右侧：操作按钮 -->
        <div class="header-right">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="showCreateDialog"
          >
            手动创建
          </el-button>
          <el-button
            type="success"
            size="small"
            icon="el-icon-refresh"
            :loading="autoCreateLoading"
            @click="autoCreateTracking"
          >
            自动创建
          </el-button>
        </div>
      </div>

      <!-- 搜索过滤栏 -->
      <div class="filter-row">
        <el-form :inline="true" :model="searchForm" class="compact-form">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.search"
              placeholder="订单号/交易号/客户"
              size="mini"
              style="width: 180px"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>

          <el-form-item label="填写状态">
            <el-select
              v-model="searchForm.filling_status"
              placeholder="请选择"
              size="mini"
              style="width: 100px"
              clearable
            >
              <el-option label="全部" value="" />
              <el-option label="待填写" value="pending" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </el-form-item>

          <el-form-item label="完成情况">
            <el-select
              v-model="searchForm.completion_status"
              placeholder="请选择"
              size="mini"
              style="width: 100px"
              clearable
            >
              <el-option label="全部" value="" />
              <el-option label="未开始" value="not_started" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="mini" @click="handleSearch">搜索</el-button>
            <el-button size="mini" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        style="width: 100%"
        row-key="id"
        :row-class-name="getRowClassName"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="order_no" label="订单单号" width="140" fixed="left">
          <template slot-scope="scope">
            <el-link :underline="false" type="primary" @click="viewOrderDetail(scope.row)">
              {{ scope.row.order_no }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column prop="reference_number" label="平台交易号" width="160">
          <template slot-scope="scope">
            <span class="transaction-number">{{ scope.row.reference_number }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="transaction_amount" label="交易金额" width="120" align="right" sortable="custom">
          <template slot-scope="scope">
            <span class="amount">
              {{ scope.row.currency }} {{ formatAmount(scope.row.transaction_amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="production_order" label="生产单(PI)" width="180">
          <template slot-scope="scope">
            <div v-if="scope.row.production_order">
              <span class="link-type" @click="selectProductionOrder(scope.row)">
                {{ scope.row.production_order.name }}
              </span>
              <a
                v-if="scope.row.production_order.token"
                href="javascript:void(0);"
                class="view-link"
                title="查看生产单"
                @click="openProductionOrderView(scope.row.production_order.token)"
              >
                [查看]
              </a>
            </div>
            <el-button
              v-else
              type="text"
              size="small"
              @click="selectProductionOrder(scope.row)"
            >
              选择生产单
            </el-button>
          </template>
        </el-table-column>

        <el-table-column prop="shipping_inquiry" label="物流单号" width="180">
          <template slot-scope="scope">
            <div v-if="scope.row.shipping_inquiry">
              <span class="link-type" @click="selectShippingInquiry(scope.row)">
                {{ scope.row.shipping_inquiry.tracking_no }}
              </span>
              <a
                v-if="scope.row.shipping_inquiry.tracking_no"
                href="javascript:void(0);"
                class="view-link"
                title="在17Track查看物流"
                @click="open17TrackView(scope.row.shipping_inquiry.tracking_no)"
              >
                [17Track]
              </a>
            </div>
            <el-button
              v-else
              type="text"
              size="small"
              @click="selectShippingInquiry(scope.row)"
            >
              选择物流单
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="filling_status" label="绑定情况" width="120" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.filling_status"
              size="mini"
              style="width: 100px"
              @change="quickUpdateStatus(scope.row, 'filling_status', scope.row.filling_status)"
            >
              <el-option label="待填写" value="pending" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="completion_status" label="支付平台" width="120" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.completion_status"
              size="mini"
              style="width: 100px"
              @change="quickUpdateStatus(scope.row, 'completion_status', scope.row.completion_status)"
            >
              <el-option label="未开始" value="not_started" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="assigned_to_name" label="财务" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.assigned_to_name || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="sales_manager_name" label="销售" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.sales_manager_name || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="payment_file" label="结算文件" width="140">
          <template slot-scope="scope">
            <span
              v-if="scope.row.payment_file"
              class="link-type"
              @click="viewPaymentFile(scope.row)"
            >
              查看
            </span>
            <el-button
              v-else
              type="text"
              size="small"
              @click="selectPaymentFile(scope.row)"
            >
              选择文件
            </el-button>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="160" sortable="custom">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="editTracking(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="success"
              @click="viewDetails(scope.row)"
            >
              详情
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="deleteTracking(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑/创建对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item v-if="!editForm.id" label="财务记录" prop="finance_record_id">
              <el-select
                v-model="editForm.finance_record_id"
                placeholder="请选择财务记录"
                style="width: 100%"
                filterable
                @change="onFinanceRecordChange"
              >
                <el-option
                  v-for="item in financeRecords"
                  :key="item.id"
                  :label="`${item.crmorder_order_no || '未知订单'} - ${item.reference_number} (${item.currency} ${item.amount})`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="填写状态" prop="filling_status">
              <el-select v-model="editForm.filling_status" style="width: 100%">
                <el-option label="待填写" value="pending" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="完成情况" prop="completion_status">
              <el-select v-model="editForm.completion_status" style="width: 100%">
                <el-option label="未开始" value="not_started" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="完成百分比" prop="completion_percentage">
              <el-slider
                v-model="editForm.completion_percentage"
                :min="0"
                :max="100"
                show-input
                style="margin-right: 20px"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="assigned_to_id">
              <el-select v-model="editForm.assigned_to_id" style="width: 100%" clearable>
                <el-option
                  v-for="user in projectUsers"
                  :key="user.id"
                  :label="user.name || user.username || '未知用户'"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="其他文件" prop="payment_file_id">
              <el-select v-model="editForm.payment_file_id" style="width: 100%" clearable>
                <el-option
                  v-for="file in paymentFiles"
                  :key="file.id"
                  :label="file.name || '未知文件'"
                  :value="file.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联生产单(PI)" prop="production_order_id">
              <el-select
                v-model="editForm.production_order_id"
                style="width: 100%"
                clearable
                placeholder="请选择PI生产单"
                filterable
                :loading="relatedDataLoading"
                loading-text="正在加载相关数据..."
              >
                <el-option
                  v-for="order in productionOrders"
                  :key="order.id"
                  :label="`${order.name || '未知生产单'} (${order.invoice_number || 'N/A'})`"
                  :value="order.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="关联物流询价" prop="shipping_inquiry_id">
              <el-select
                v-model="editForm.shipping_inquiry_id"
                style="width: 100%"
                clearable
                placeholder="请选择物流询价"
                filterable
                :loading="relatedDataLoading"
                loading-text="正在加载相关数据..."
              >
                <el-option
                  v-for="inquiry in shippingInquiries"
                  :key="inquiry.id"
                  :label="`${inquiry.tracking_no || '无跟踪号'} (${inquiry.product_name || '未知产品'})`"
                  :value="inquiry.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
            v-model="editForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="saveTracking">保存</el-button>
      </div>
    </el-dialog>

    <!-- 生产单选择对话框 -->
    <el-dialog
      title="选择生产单(PI)"
      :visible.sync="productionOrderDialogVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-loading="relatedDataLoading" element-loading-text="正在加载生产单列表...">
        <div class="current-info">
          <p><strong>当前订单：</strong>{{ currentEditingRow && currentEditingRow.order_no }} - {{ currentEditingRow && currentEditingRow.crm_order && currentEditingRow.crm_order.name || '订单信息' }}</p>
          <p><strong>当前生产单：</strong>
            <span v-if="currentEditingRow && currentEditingRow.production_order">
              {{ currentEditingRow.production_order.name }} ({{ currentEditingRow.production_order.invoice_number || 'N/A' }})
            </span>
            <span v-else class="text-muted">未关联生产单</span>
          </p>
        </div>

        <el-table
          :data="productionOrders"
          style="width: 100%; margin-top: 20px;"
          height="400"
          highlight-current-row
          @current-change="handleProductionOrderSelect"
        >
          <el-table-column label="选择" width="60">
            <template slot-scope="scope">
              <el-radio
                v-model="selectedProductionOrderId"
                :label="scope.row.id"
                @change="handleProductionOrderSelect(scope.row)"
              >&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="生产单名称" width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.name || '未知生产单' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="invoice_number" label="PI发票号" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.invoice_number || 'N/A' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="160">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.created_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getProductionOrderStateType(scope.row.state)" size="mini">
                {{ getProductionOrderStateText(scope.row.state) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.token"
                type="text"
                size="mini"
                @click="openProductionOrderView(scope.row.token)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="productionOrderDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" :disabled="!selectedProductionOrderId" @click="saveProductionOrderSelection">保存</el-button>
      </div>
    </el-dialog>

    <!-- 物流询价选择对话框 -->
    <el-dialog
      title="选择物流询价"
      :visible.sync="shippingInquiryDialogVisible"
      width="1000px"
      :close-on-click-modal="false"
    >
      <div v-loading="relatedDataLoading" element-loading-text="正在加载物流询价列表...">
        <div class="current-info">
          <p><strong>当前订单：</strong>{{ currentEditingRow && currentEditingRow.order_no }} - {{ currentEditingRow && currentEditingRow.crm_order && currentEditingRow.crm_order.name || '订单信息' }}</p>
          <p><strong>当前物流单：</strong>
            <span v-if="currentEditingRow && currentEditingRow.shipping_inquiry">
              {{ currentEditingRow.shipping_inquiry.tracking_no }} ({{ currentEditingRow.shipping_inquiry.product_name || 'N/A' }})
            </span>
            <span v-else class="text-muted">未关联物流询价</span>
          </p>
        </div>

        <el-table
          :data="shippingInquiries"
          style="width: 100%; margin-top: 20px;"
          height="400"
          highlight-current-row
          @current-change="handleShippingInquirySelect"
        >
          <el-table-column label="选择" width="60">
            <template slot-scope="scope">
              <el-radio
                v-model="selectedShippingInquiryId"
                :label="scope.row.id"
                @change="handleShippingInquirySelect(scope.row)"
              >&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="tracking_no" label="跟踪号" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.tracking_no || '无跟踪号' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="product_name" label="产品名称" width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.product_name || '未知产品' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="shipping_method" label="物流方式" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.shipping_method || 'N/A' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.weight || 'N/A' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="费用" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.cost || 'N/A' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="160">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.created_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.tracking_no"
                type="text"
                size="mini"
                @click="open17TrackView(scope.row.tracking_no)"
              >
                17Track
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="shippingInquiryDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" :disabled="!selectedShippingInquiryId" @click="saveShippingInquirySelection">保存</el-button>
      </div>
    </el-dialog>

    <!-- CRMPaymentFileDrawer 组件集成 -->
    <crmpaymentfile-drawer
      :visible="paymentFileDrawerVisible"
      :order_no="selectedOrderNo"
      :order_name="selectedOrderName"
      @close="onPaymentFileDrawerClose"
    />

    <!-- CRM订单详情对话框 -->
    <crmorderdetail
      :order_data="selectedOrderData"
      :order-states="defaultOrderStates"
      :show-able="orderDetailVisible"
      @close="orderDetailVisible = false"
    />
  </div>
</template>

<script>
import {
  getSettlementTrackingList,
  createSettlementTracking,
  updateSettlementTracking,
  deleteSettlementTracking,
  autoCreateTrackingFromFinance,
  getProductionOrdersPI,
  getShippingInquiries
} from '@/api/crm/settlement_tracking'
import { Get as getFinanceRecords } from '@/api/crm/crmorderfinance'
import { Get as getPaymentFiles } from '@/api/crm/crmpaymentfile'
import { CRMGetProjectUsers as getProjectUsers } from '@/api/crm/crmmanage'
import CRMPaymentFileDrawer from '@/views/crm/elements/crmpaymentfile'
import CRMOrderDetail from '@/views/crm/elements/crmorderdetail'

export default {
  name: 'SettlementTracking',
  components: {
    'crmpaymentfile-drawer': CRMPaymentFileDrawer,
    'crmorderdetail': CRMOrderDetail
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      tableLoading: false,

      // 分页数据
      currentPage: 1,
      pageSize: 20,
      total: 0,

      // 搜索表单
      searchForm: {
        search: '',
        filling_status: 'pending', // 默认显示待填写状态
        completion_status: '',
        ordering: '' // 排序字段
      },

      // 统计数据
      stats: null,

      // 对话框相关
      dialogVisible: false,
      saveLoading: false,

      // 编辑表单
      editForm: {
        id: null,
        finance_record_id: null,
        filling_status: 'pending',
        completion_status: 'not_started',
        completion_percentage: 0,
        assigned_to_id: null,
        payment_file_id: null,
        production_order_id: null,
        shipping_inquiry_id: null,
        notes: '',
        review_notes: ''
      },

      // 表单验证规则
      editRules: {
        finance_record_id: [
          { required: true, message: '请选择财务记录', trigger: 'change' }
        ],
        filling_status: [
          { required: true, message: '请选择填写状态', trigger: 'change' }
        ],
        completion_status: [
          { required: true, message: '请选择完成情况', trigger: 'change' }
        ]
      },

      // 选项数据
      financeRecords: [],
      paymentFiles: [],
      projectUsers: [],
      productionOrders: [], // PI类型生产单列表
      shippingInquiries: [], // 物流询价列表

      // 其他状态
      autoCreateLoading: false,
      relatedDataLoading: false, // 相关数据加载状态

      // 生产单选择对话框
      productionOrderDialogVisible: false,
      productionOrderForm: {
        production_order_id: null
      },
      selectedProductionOrderId: null, // 表格选择的生产单ID
      currentEditingRow: null, // 当前正在编辑的行数据

      // 物流询价选择对话框
      shippingInquiryDialogVisible: false,
      shippingInquiryForm: {
        shipping_inquiry_id: null
      },
      selectedShippingInquiryId: null, // 表格选择的物流询价ID

      // 支付文件抽屉相关
      paymentFileDrawerVisible: false,
      selectedOrderNo: '',
      selectedOrderName: '',

      // 订单详情相关
      orderDetailVisible: false,
      selectedOrderData: null,
      defaultOrderStates: [
        { id: 1, name: '待处理' },
        { id: 2, name: '处理中' },
        { id: 3, name: '已完成' }
      ]
    }
  },

  computed: {
    // 计算对话框标题
    dialogTitle() {
      return this.editForm.id ? '编辑结算跟踪' : '创建结算跟踪'
    }
  },

  mounted() {
    this.handleUrlParams()
    this.loadData()
    this.loadOptions()
  },

  methods: {
    // 获取行的样式类名
    getRowClassName({ row }) {
      if (row.filling_status === 'completed') {
        return 'completed-row'
      }
      return ''
    },

    // 处理URL参数
    handleUrlParams() {
      const urlParams = new URLSearchParams(window.location.hash.split('?')[1])

      // 处理订单号参数
      const orderNo = urlParams.get('order_no')
      if (orderNo) {
        this.searchForm.search = orderNo
        // 延迟执行搜索，确保组件已经完全加载
        this.$nextTick(() => {
          console.log('URL参数设置搜索条件:', orderNo)
        })
      }

      // 处理其他可能的参数
      const fillingStatus = urlParams.get('filling_status')
      if (fillingStatus) {
        this.searchForm.filling_status = fillingStatus
      }

      const completionStatus = urlParams.get('completion_status')
      if (completionStatus) {
        this.searchForm.completion_status = completionStatus
      }
    },
    // 加载数据
    async loadData() {
      this.tableLoading = true
      try {
        const params = {
          page: this.currentPage,
          pagesize: this.pageSize,
          ...this.searchForm
        }

        const response = await getSettlementTrackingList(params)
        if (response.success) {
          this.tableData = response.data.list
          this.total = response.data.pagination.total
          this.stats = response.data.stats
        } else {
          this.$message.error(response.msg || '加载数据失败')
        }
      } catch (error) {
        this.$message.error('加载数据失败: ' + error.message)
      } finally {
        this.tableLoading = false
      }
    },

    // 快速更新状态
    async quickUpdateStatus(row, field, value) {
      try {
        const updateData = {
          id: row.id,
          [field]: value
        }
        const response = await updateSettlementTracking(updateData)
        if (response.success) {
          this.$message.success('状态更新成功')
          // 更新本地数据
          row[field] = value
          // 如果是完成状态更新，也更新进度
          if (field === 'completion_status') {
            if (value === 'completed') {
              row.completion_percentage = 100
            } else if (value === 'not_started') {
              row.completion_percentage = 0
            }
          }
        } else {
          this.$message.error(response.msg || '状态更新失败')
          // 恢复原值
          this.loadData()
        }
      } catch (error) {
        console.error('快速更新状态失败:', error)
        this.$message.error('状态更新失败: ' + error.message)
        // 恢复原值
        this.loadData()
      }
    },

    // 根据订单号加载相关选项
    async loadOrderRelatedOptions(orderNo) {
      this.relatedDataLoading = true
      try {
        // 获取该订单相关的生产单
        const productionResponse = await getProductionOrdersPI({ order_no: orderNo })
        if (productionResponse.success && productionResponse.data) {
          this.productionOrders = Array.isArray(productionResponse.data) ? productionResponse.data : []
        }

        // 获取该订单相关的物流询价
        const shippingResponse = await getShippingInquiries({ order_no: orderNo })
        if (shippingResponse.success && shippingResponse.data) {
          this.shippingInquiries = Array.isArray(shippingResponse.data) ? shippingResponse.data : []
        }
      } catch (error) {
        console.error('加载订单相关选项失败:', error)
        this.$message.error('加载相关数据失败')
      } finally {
        this.relatedDataLoading = false
      }
    },

    // 加载选项数据
    async loadOptions() {
      try {
        // 加载财务记录（只获取收入且有交易号的记录）
        const financeResponse = await getFinanceRecords(null, 'is_income=true&has_reference=true&pagesize=200')
        if (financeResponse.success && financeResponse.data && financeResponse.data.data) {
          this.financeRecords = Array.isArray(financeResponse.data.data) ? financeResponse.data.data : []
        } else {
          this.financeRecords = []
        }

        // 加载支付文件
        const paymentResponse = await getPaymentFiles(null, 'pagesize=200')
        if (paymentResponse.success && paymentResponse.data && paymentResponse.data.data) {
          this.paymentFiles = Array.isArray(paymentResponse.data.data) ? paymentResponse.data.data : []
        } else {
          this.paymentFiles = []
        }

        // 加载项目用户
        const usersResponse = await getProjectUsers()
        if (usersResponse.success && usersResponse.data) {
          this.projectUsers = Array.isArray(usersResponse.data) ? usersResponse.data : []
        } else {
          this.projectUsers = []
        }

        // 加载PI类型生产单
        const productionResponse = await getProductionOrdersPI()
        if (productionResponse.success && productionResponse.data) {
          this.productionOrders = Array.isArray(productionResponse.data) ? productionResponse.data : []
        } else {
          this.productionOrders = []
        }

        // 加载物流询价（可以根据订单号过滤）
        const shippingResponse = await getShippingInquiries()
        if (shippingResponse.success && shippingResponse.data) {
          this.shippingInquiries = Array.isArray(shippingResponse.data) ? shippingResponse.data : []
        } else {
          this.shippingInquiries = []
        }
      } catch (error) {
        console.error('加载选项数据失败:', error)
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        search: '',
        filling_status: '',
        completion_status: '',
        ordering: ''
      }
      this.handleSearch()
    },

    // 分页相关
    handleSizeChange(size) {
      this.pageSize = size
      this.loadData()
    },

    handleCurrentChange(page) {
      this.currentPage = page
      this.loadData()
    },

    // 排序
    handleSortChange(sort) {
      console.log('排序变化:', sort)
      if (sort.prop && sort.order) {
        // 将Element UI的排序顺序转换为Django的ordering格式
        const order = sort.order === 'ascending' ? '' : '-'
        this.searchForm.ordering = order + sort.prop
      } else {
        // 取消排序
        this.searchForm.ordering = ''
      }
      this.currentPage = 1
      this.loadData()
    },

    // 显示创建对话框
    showCreateDialog() {
      this.resetEditForm()
      this.dialogVisible = true
    },

    // 编辑跟踪记录
    editTracking(row) {
      this.editForm = {
        id: row.id,
        finance_record_id: row.finance_record?.id,
        filling_status: row.filling_status,
        completion_status: row.completion_status,
        completion_percentage: row.completion_percentage,
        assigned_to_id: row.assigned_to_id,
        payment_file_id: row.payment_file?.id,
        production_order_id: row.production_order?.id,
        shipping_inquiry_id: row.shipping_inquiry?.id,
        notes: row.notes || '',
        review_notes: row.review_notes || ''
      }

      // 先显示弹窗
      this.dialogVisible = true

      // 异步加载订单相关的生产单和物流询价
      if (row.order_no) {
        this.loadOrderRelatedOptions(row.order_no)
      }
    },

    // 保存跟踪记录
    async saveTracking() {
      this.$refs.editForm.validate(async(valid) => {
        if (valid) {
          this.saveLoading = true
          try {
            let response
            if (this.editForm.id) {
              response = await updateSettlementTracking(this.editForm)
            } else {
              response = await createSettlementTracking(this.editForm)
            }

            if (response.success) {
              this.$message.success(response.msg || '保存成功')
              this.dialogVisible = false
              this.loadData()
            } else {
              this.$message.error(response.msg || '保存失败')
            }
          } catch (error) {
            this.$message.error('保存失败: ' + error.message)
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 删除跟踪记录
    deleteTracking(row) {
      this.$confirm(`确定要删除订单 ${row.order_no} 的结算跟踪记录吗？`, '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const response = await deleteSettlementTracking(row.id)
          if (response.success) {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败: ' + error.message)
        }
      })
    },

    // 自动创建跟踪记录
    async autoCreateTracking() {
      this.autoCreateLoading = true
      try {
        const response = await autoCreateTrackingFromFinance()
        if (response.success) {
          this.$message.success(`${response.msg}，已创建 ${response.data.created_count} 条记录`)
          this.loadData()
        } else {
          this.$message.error(response.msg || '自动创建失败')
        }
      } catch (error) {
        this.$message.error('自动创建失败: ' + error.message)
      } finally {
        this.autoCreateLoading = false
      }
    },

    // 查看订单详情
    async viewOrderDetail(row) {
      console.log('查看CRM订单详情:', row)
      console.log('row.crm_order:', row.crm_order)

      // 检查CRM订单数据是否存在
      if (row.crm_order && row.crm_order.id) {
        console.log('设置订单数据:', row.crm_order)
        // 使用深拷贝创建新的对象引用，确保子组件能够检测到变化
        this.selectedOrderData = JSON.parse(JSON.stringify(row.crm_order))
        this.orderDetailVisible = true
        console.log('orderDetailVisible 设置为:', this.orderDetailVisible)
        console.log('selectedOrderData 设置为:', this.selectedOrderData)
        console.log('条件检查 selectedOrderData && orderDetailVisible:', this.selectedOrderData && this.orderDetailVisible)
        // 使用 nextTick 确保 DOM 更新后再检查
        this.$nextTick(() => {
          console.log('nextTick - orderDetailVisible:', this.orderDetailVisible)
          console.log('nextTick - selectedOrderData:', this.selectedOrderData)
          console.log('DOM元素检查:', document.querySelector('.el-drawer'))
          console.log('Vue组件检查:', this.$children.find(c => c.$options.name === 'Crmorderdetail'))
        })
      } else {
        console.log('没有完整的订单数据')
        // 如果没有完整数据，尝试从finance_record获取订单ID并调用API
        const orderId = row.finance_record?.crm_order_id
        if (!orderId) {
          this.$message.warning('该记录缺少CRM订单ID信息')
          return
        }

        try {
          // 这里需要调用CRM订单详情API，但我们先用现有数据
          this.$message.warning('订单详情数据不完整，请在CRM订单管理中查看详细信息')
          return
        } catch (error) {
          console.error('获取订单详情失败:', error)
          this.$message.error('获取订单详情失败')
        }
      }
    },

    // 查看详情
    viewDetails(row) {
      // TODO: 实现查看详情
      console.log('查看详情:', row)
    },

    // 查看支付文件
    viewPaymentFile(row) {
      if (!row.order_no) {
        this.$message.warning('该记录缺少订单号信息')
        return
      }
      this.selectedOrderNo = row.order_no
      // 注意：根据后端 to_dict() 方法，crm_order 是在根级别
      this.selectedOrderName = row.crm_order?.name || row.finance_record?.vendor_or_customer || row.order_no || '未知订单'
      this.paymentFileDrawerVisible = true
    },

    // 选择支付文件
    selectPaymentFile(row) {
      // 设置当前编辑的记录
      this.editForm = {
        id: row.id,
        finance_record_id: row.finance_record?.id,
        filling_status: row.filling_status,
        completion_status: row.completion_status,
        completion_percentage: row.completion_percentage,
        assigned_to_id: row.assigned_to_id,
        payment_file_id: row.payment_file?.id,
        notes: row.notes || '',
        review_notes: row.review_notes || ''
      }

      // 打开编辑对话框，让用户选择支付文件
      this.dialogVisible = true

      // 可以考虑添加快捷操作：直接创建新的支付文件
      this.$confirm('您希望选择现有的支付文件还是为此订单创建新的支付文件？', '选择操作', {
        distinguishCancelAndClose: true,
        confirmButtonText: '选择现有文件',
        cancelButtonText: '创建新文件',
        type: 'info'
      }).then(() => {
        // 用户选择现有文件 - 对话框已经打开，显示支付文件选择器
        this.$message.info('请在下方选择已存在的支付文件')
      }).catch(action => {
        if (action === 'cancel') {
          // 用户选择创建新文件 - 打开支付文件创建器
          this.selectedOrderNo = row.order_no
          // 注意：根据后端 to_dict() 方法，crm_order 是在根级别
          this.selectedOrderName = row.crm_order?.name || row.finance_record?.vendor_or_customer || row.order_no || '未知订单'
          this.paymentFileDrawerVisible = true
          this.dialogVisible = false
        } else {
          // 用户点击了关闭按钮
          this.dialogVisible = false
        }
      })
    },

    // 选择生产单
    async selectProductionOrder(row) {
      // 保存当前编辑的行数据
      this.currentEditingRow = row

      // 初始化选择状态
      this.selectedProductionOrderId = row.production_order && row.production_order.id || null
      this.productionOrderForm = {
        production_order_id: this.selectedProductionOrderId
      }

      // 先显示对话框
      this.productionOrderDialogVisible = true

      // 异步加载订单相关的生产单列表
      if (row.order_no) {
        await this.loadOrderRelatedOptions(row.order_no)
        // 数据加载完成后，如果没有当前选中且有数据，默认选中第一个
        if (!this.selectedProductionOrderId && this.productionOrders.length > 0) {
          this.selectedProductionOrderId = this.productionOrders[0].id
          this.productionOrderForm.production_order_id = this.selectedProductionOrderId
        }
      }
    },

    // 选择物流询价
    async selectShippingInquiry(row) {
      // 保存当前编辑的行数据
      this.currentEditingRow = row

      // 初始化选择状态
      this.selectedShippingInquiryId = row.shipping_inquiry && row.shipping_inquiry.id || null
      this.shippingInquiryForm = {
        shipping_inquiry_id: this.selectedShippingInquiryId
      }

      // 先显示对话框
      this.shippingInquiryDialogVisible = true

      // 异步加载订单相关的物流询价列表
      if (row.order_no) {
        await this.loadOrderRelatedOptions(row.order_no)
        // 数据加载完成后，如果没有当前选中且有数据，默认选中第一个
        if (!this.selectedShippingInquiryId && this.shippingInquiries.length > 0) {
          this.selectedShippingInquiryId = this.shippingInquiries[0].id
          this.shippingInquiryForm.shipping_inquiry_id = this.selectedShippingInquiryId
        }
      }
    },

    // 保存生产单选择
    async saveProductionOrderSelection() {
      this.saveLoading = true
      try {
        const updateData = {
          id: this.currentEditingRow.id,
          production_order_id: this.selectedProductionOrderId
        }

        const response = await updateSettlementTracking(updateData)

        if (response.success) {
          this.$message.success('生产单关联成功')
          this.productionOrderDialogVisible = false
          this.selectedProductionOrderId = null
          this.loadData() // 重新加载表格数据
        } else {
          this.$message.error(response.msg || '关联失败')
        }
      } catch (error) {
        console.error('保存生产单选择失败:', error)
        this.$message.error('关联失败: ' + error.message)
      } finally {
        this.saveLoading = false
      }
    },

    // 保存物流询价选择
    async saveShippingInquirySelection() {
      this.saveLoading = true
      try {
        const updateData = {
          id: this.currentEditingRow.id,
          shipping_inquiry_id: this.selectedShippingInquiryId
        }

        const response = await updateSettlementTracking(updateData)

        if (response.success) {
          this.$message.success('物流询价关联成功')
          this.shippingInquiryDialogVisible = false
          this.selectedShippingInquiryId = null
          this.loadData() // 重新加载表格数据
        } else {
          this.$message.error(response.msg || '关联失败')
        }
      } catch (error) {
        console.error('保存物流询价选择失败:', error)
        this.$message.error('关联失败: ' + error.message)
      } finally {
        this.saveLoading = false
      }
    },

    // 重置编辑表单
    resetEditForm() {
      this.editForm = {
        id: null,
        finance_record_id: null,
        filling_status: 'pending',
        completion_status: 'not_started',
        completion_percentage: 0,
        assigned_to_id: null,
        payment_file_id: null,
        notes: '',
        review_notes: ''
      }
      this.$nextTick(() => {
        if (this.$refs.editForm) {
          this.$refs.editForm.clearValidate()
        }
      })
    },

    // 财务记录变化事件
    onFinanceRecordChange(financeRecordId) {
      const record = this.financeRecords.find(r => r.id === financeRecordId)
      if (record) {
        // 可以根据财务记录自动填充一些信息
        console.log('选择的财务记录:', record)
      }
    },

    // 支付文件抽屉关闭事件
    onPaymentFileDrawerClose() {
      this.paymentFileDrawerVisible = false
      this.selectedOrderNo = ''
      this.selectedOrderName = ''
      // 可以在这里刷新数据或处理其他逻辑
    },

    // 格式化金额
    formatAmount(amount) {
      return parseFloat(amount).toLocaleString()
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString()
    },

    // 获取填写状态类型
    getFillingStatusType(status) {
      const typeMap = {
        'pending': 'warning',
        'filling': 'primary',
        'completed': 'success',
        'verified': 'success',
        'cancelled': 'danger'
      }
      return typeMap[status] || 'info'
    },

    // 获取填写状态文本
    getFillingStatusText(status) {
      const textMap = {
        'pending': '待填写',
        'filling': '填写中',
        'completed': '已完成',
        'verified': '已审核',
        'cancelled': '已取消'
      }
      return textMap[status] || status
    },

    // 获取完成状态类型
    getCompletionStatusType(status) {
      const typeMap = {
        'not_started': 'info',
        'in_progress': 'primary',
        'completed': 'success',
        'need_review': 'warning',
        'rejected': 'danger'
      }
      return typeMap[status] || 'info'
    },

    // 获取完成状态文本
    getCompletionStatusText(status) {
      const textMap = {
        'not_started': '未开始',
        'in_progress': '进行中',
        'completed': '已完成',
        'need_review': '需要审核',
        'rejected': '已驳回'
      }
      return textMap[status] || status
    },

    // 获取进度条颜色
    getProgressColor(percentage) {
      if (percentage < 30) return '#f56c6c'
      if (percentage < 70) return '#e6a23c'
      return '#67c23a'
    },

    // 打开生产单查看链接
    openProductionOrderView(token) {
      if (!token) {
        this.$message.warning('此生产单尚未生成查看链接')
        return
      }
      const url = `https://po.lianf.com/${token}`
      window.open(url, '_blank')
    },

    // 打开17Track物流查看链接
    open17TrackView(trackingNo) {
      if (!trackingNo) {
        this.$message.warning('缺少有效的物流单号')
        return
      }
      const url = `https://t.17track.net/en#nums=${trackingNo}`
      window.open(url, '_blank')
    },

    // 处理生产单选择
    handleProductionOrderSelect(row) {
      if (row) {
        this.selectedProductionOrderId = row.id
        this.productionOrderForm.production_order_id = row.id
      }
    },

    // 处理物流询价选择
    handleShippingInquirySelect(row) {
      if (row) {
        this.selectedShippingInquiryId = row.id
        this.shippingInquiryForm.shipping_inquiry_id = row.id
      }
    },

    // 获取生产单状态类型
    getProductionOrderStateType(state) {
      const stateMap = {
        '1': 'info', // 待处理
        '2': 'warning', // 处理中
        '3': 'success', // 已完成
        '4': 'success' // PI文件
      }
      return stateMap[state] || 'info'
    },

    // 获取生产单状态文本
    getProductionOrderStateText(state) {
      const stateMap = {
        '1': '待处理',
        '2': '处理中',
        '3': '已完成',
        '4': 'PI文件'
      }
      return stateMap[state] || '未知'
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.page-header-compact {
  background: white;
  border-radius: 4px;
  padding: 15px 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-row {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15px;

    .header-left {
      .page-title {
        font-size: 18px;
        color: #303133;
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
      }

      .stats-inline {
        display: flex;
        gap: 15px;

        .stat-item {
          font-size: 12px;
          color: #606266;

          strong {
            color: #303133;
          }

          &.pending strong {
            color: #E6A23C;
          }

          &.processing strong {
            color: #409EFF;
          }

          &.completed strong {
            color: #67C23A;
          }
        }
      }
    }

    .header-right {
      display: flex;
      gap: 8px;
    }
  }

  .filter-row {
    border-top: 1px solid #EBEEF5;
    padding-top: 15px;

    .compact-form {
      .el-form-item {
        margin-right: 15px;
        margin-bottom: 0;

        .el-form-item__label {
          font-size: 12px;
          padding-right: 8px;
        }
      }
    }
  }
}

.table-container {
  background: white;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.transaction-number {
  font-family: monospace;
  font-size: 12px;
  color: #606266;
}

.amount {
  font-weight: bold;
  color: #1EB7E6;
}

.dialog-footer {
  text-align: right;
}

// 表格内的进度条样式调整
::v-deep .el-progress-bar__outer {
  height: 8px !important;
}

::v-deep .el-progress__text {
  font-size: 12px !important;
}

// 已完成条目的行样式
::v-deep .el-table .completed-row {
  background-color: #f0f9ff !important;
  border-left: 4px solid #1EB7E6 !important;
}

::v-deep .el-table .completed-row:hover > td {
  background-color: #e6f4ff !important;
}

// 已完成状态的文字样式
::v-deep .completed-row .el-select .el-input__inner {
  background-color: #f0f9ff;
  border-color: #1EB7E6;
  color: #1EB7E6;
  font-weight: bold;
}

// 链接样式
.link-type {
  color: #409EFF;
  cursor: pointer;
}

.link-type:hover {
  color: #66b1ff;
}

// 文本样式
.text-muted {
  color: #909399;
  font-style: italic;
}

// 查看链接样式
.view-link {
  color: #67c23a;
  text-decoration: none;
  font-size: 12px;
  margin-left: 8px;
  font-weight: 500;
}

.view-link:hover {
  color: #85ce61;
  text-decoration: underline;
}

// 表格边框线条样式
::v-deep .el-table {
  border: 1px solid #EBEEF5;
}

::v-deep .el-table td,
::v-deep .el-table th {
  border-right: 1px solid #EBEEF5;
}

::v-deep .el-table th {
  border-bottom: 1px solid #EBEEF5;
}

::v-deep .el-table .el-table__body tr:last-child td {
  border-bottom: 1px solid #EBEEF5;
}

// 选择对话框当前信息样式
.current-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  border-left: 4px solid #409EFF;

  p {
    margin: 8px 0;
    color: #606266;

    strong {
      color: #303133;
      margin-right: 8px;
    }
  }
}
</style>
